package org.lalib.controller.action;

import java.util.ArrayList;
import java.util.List;

import org.lalib.acquire.IControllerAction;
import org.lalib.controller.form.CCookerForm;
import org.lalib.controller.form.CCookerForm.CookerFoodBean;
import org.lalib.controller.service.CFoodService;
import org.lalib.controller.service.COrderService;
import org.lalib.controller.service.CUserService;
import org.lalib.entity.object.EFood;
import org.lalib.entity.object.EOrder;
import org.lalib.entity.object.EUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

@Scope("request")
@Controller("cCookerAction")
public class CCookerAction implements IControllerAction {

	private static final long serialVersionUID = 1L;

	@Autowired
	CCookerForm cCookerForm;

	@Autowired
	COrderService cOrderService;

	@Autowired
	CUserService cUserService;

	@Autowired
	CFoodService cFoodService;

	public String init(EUser user) {
		reset(user);
		cCookerForm.setUser(user);
		return "mobileCooker";
	}

	private void reset(EUser user) {
		user = (EUser) cUserService.getUserById(user.getId());
		List<EFood> foods = user.getFoods();
		List<EOrder> orders = cOrderService.getCurrentOrdersForCooker(foods);
		cCookerForm.setOrders(orders);
		cCookerForm.setCookerFoodBeans(getCookerFoodBeans(orders));
	}

	public void approve() {
		List<CookerFoodBean> beans = cCookerForm.getCookerFoodBeans();

		for (CookerFoodBean cookerFoodBean : beans) {
			if (cookerFoodBean.isSelected()) {
				EOrder order = cOrderService.getOrderById(cookerFoodBean.getOrderId());
				order.setHazirlandi(true);
				cOrderService.update(order);
			}
		}
		reset(cCookerForm.getUser());
	}

	private List<CookerFoodBean> getCookerFoodBeans(List<EOrder> orders) {
		List<CookerFoodBean> cookerFoodBeans = new ArrayList<>();
		for (EOrder order : orders) {
			EFood food = order.geteFood();
			food = cFoodService.getFoodById(food.getId());
			cookerFoodBeans.add(cCookerForm.new CookerFoodBean(food.getName(), order.getId()));
		}
		return cookerFoodBeans;
	}

	public String logout() {
		return "mobileLogin";
	}

	public String goBack() {
		return init(cCookerForm.getUser());
	}

	public String showOrderDetail(CookerFoodBean cookerFoodBean) {
		EOrder order = cOrderService.getOrderById(cookerFoodBean.getOrderId());
		cCookerForm.setCurrentOrder(order);
		EFood food = order.geteFood();
		food = cFoodService.getFoodById(food.getId());
		cCookerForm.setFoodName(food.getName());
		cCookerForm.setDescription(order.getExplanation());
		return "mobileCookerDetails";
	}
}